<template>
  <div class="quotation-page" style="height: 800px;">
    <!-- 顶部信息及操作区域 -->
    <div class="top-bar">
      <div class="title-area">
        <span class="page-title">报价单</span>
        <span class="doc-number">单据编号：XSBJ20250625001</span>
        <span> <el-button type="text" @click="recording">记录</el-button></span>
      </div>
      <div class="btn-group">
        <el-button type="primary" @click="handleSaveAndNew">保存并新增</el-button>
        <el-button type="success" @click="handleSave">保存</el-button>
        <el-button type="warning" @click="handleApprove">审核</el-button>
        <el-dropdown>
          <el-button type="text">更多</el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item>操作1</el-dropdown-item>
              <el-dropdown-item>操作2</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>

    <!-- 基础信息表单区域 -->
    <el-form :model="form" label-width="100px" class="base-info-form">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="单据日期">
            <el-date-picker
              v-model="form.documentDate"
              type="date"
              value-format="YYYY/MM/DD"
              placeholder="选择日期"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="报价类型">
            <el-select v-model="form.quotationType" placeholder="请选择">
              <el-option label="客户" value="customer" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="报价主体">
            <el-select v-model="form.quotationSubject" placeholder="请选择">
              <el-option label="主体1" value="subject1" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="业务员">
            <el-select v-model="form.salesman" placeholder="请选择">
              <el-option label="业务员1" value="salesman1" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="有效日期">
            <el-date-picker
              v-model="form.effectiveDate"
              type="daterange"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY/MM/DD HH:mm:ss"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="客户地址">
            <el-select v-model="form.customerAddress" placeholder="请选择">
              <el-option label="地址1" value="address1" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="是否报价">
            <el-switch v-model="form.isQuotation" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="扫码枪录入">
            <el-switch v-model="form.scanGunInput" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 商品表格区域（含合计行） -->
    <div class="table-wrapper">
      <div class="table-scroll" style="height: 400px; overflow: auto;">
        <el-table
          :data="displayData"
          border
          style="width: 100%"
          :header-cell-style="{ background: '#fafafa', position: 'sticky', top: '0', zIndex: 1 }"
          :row-style="{ height: '60px' }"
          @cell-click="handleCellClick"
        >
          <el-table-column label="序号" align="center" width="60">
            <template #default="scope">
              {{ scope.row.index }}
            </template>
          </el-table-column>
          <el-table-column label="商品名称" align="center" width="120">
            <template #header>
              <div class="header-with-btn">
                <span>商品名称</span>
                <el-button
                  type="primary"
                  icon="el-icon-upload"
                  @click="openGoodsDialog"
                  size="mini"
                >导入</el-button>
              </div>
            </template>
            <template #default="scope">
              <div v-if="!isEditing(scope.row, 'productName')" @click.stop="startEditing(scope.row, 'productName')">
                {{ scope.row.productName || ' ' }}
              </div>
              <el-input
                v-else
                v-model="scope.row.productName"
                size="mini"
                @blur="stopEditing"
                @keyup.enter="stopEditing"
              />
            </template>
          </el-table-column>
          <el-table-column label="商品图片" align="center" width="100">
            <template #default="scope">
              <el-image
                v-if="scope.row.productImage"
                :src="scope.row.productImage"
                fit="cover"
                width="40"
                height="40"
              />
              <span v-else>无图</span>
            </template>
          </el-table-column>
          <el-table-column label="品牌" align="center" width="100">
            <template #default="scope">
              <div v-if="!isEditing(scope.row, 'brand')" @click.stop="startEditing(scope.row, 'brand')">
                {{ scope.row.brand || '' }}
              </div>
              <el-input
                v-else
                v-model="scope.row.brand"
                size="mini"
                @blur="stopEditing"
                @keyup.enter="stopEditing"
              />
            </template>
          </el-table-column>
          <el-table-column label="属性" align="center" width="100">
            <template #default="scope">
              <div v-if="!isEditing(scope.row, 'attribute')" @click.stop="startEditing(scope.row, 'attribute')">
                {{ scope.row.attribute || '' }}
              </div>
              <el-input
                v-else
                v-model="scope.row.attribute"
                size="mini"
                @blur="stopEditing"
                @keyup.enter="stopEditing"
              />
            </template>
          </el-table-column>
          <el-table-column label="单位" align="center" width="80">
            <template #default="scope">
              <div v-if="!isEditing(scope.row, 'unit')" @click.stop="startEditing(scope.row, 'unit')">
                {{ scope.row.unit || '' }}
              </div>
              <el-input
                v-else
                v-model="scope.row.unit"
                size="mini"
                @blur="stopEditing"
                @keyup.enter="stopEditing"
              />
            </template>
          </el-table-column>
          <el-table-column label="仓库" align="center" width="100">
            <template #default="scope">
              <div v-if="!isEditing(scope.row, 'warehouse')" @click.stop="startEditing(scope.row, 'warehouse')">
                {{ scope.row.warehouse === 'mainWarehouse' ? '主仓库' : '分仓库' || '点击选择' }}
              </div>
              <el-select
                v-else
                v-model="scope.row.warehouse"
                placeholder="选择仓库"
                size="mini"
                @blur="stopEditing"
                @change="stopEditing"
              >
                <el-option label="主仓库" value="mainWarehouse" />
                <el-option label="分仓库" value="branchWarehouse" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="数量" align="center" width="120">
            <template #header>
              <div class="header-with-btn">
                <span>数量</span>
                <el-button
                  type="text"
                  icon="el-icon-setting"
                  @click="handleBatchModify"
                  size="mini"
                >批量修改</el-button>
              </div>
            </template>
            <template #default="scope">
              <div v-if="!isEditing(scope.row, 'quantity')" @click.stop="startEditing(scope.row, 'quantity')">
                {{ scope.row.quantity || '' }}
              </div>
              <el-input
                v-else
                v-model.number="scope.row.quantity"
                size="mini"
                type="number"
                :min="0"
                @blur="stopEditing"
                @keyup.enter="stopEditing"
              />
            </template>
          </el-table-column>
          <el-table-column label="基本单位" align="center" width="100">
            <template #default="scope">
              <div v-if="!isEditing(scope.row, 'baseUnit')" @click.stop="startEditing(scope.row, 'baseUnit')">
                {{ scope.row.baseUnit || '' }}
              </div>
              <el-input
                v-else
                v-model="scope.row.baseUnit"
                size="mini"
                @blur="stopEditing"
                @keyup.enter="stopEditing"
              />
            </template>
          </el-table-column>
          <el-table-column label="基本数量" align="center" width="100">
            <template #default="scope">
              <div v-if="!isEditing(scope.row, 'baseQuantity')" @click.stop="startEditing(scope.row, 'baseQuantity')">
                {{ scope.row.baseQuantity || '' }}
              </div>
              <el-input
                v-else
                v-model.number="scope.row.baseQuantity"
                size="mini"
                type="number"
                :min="0"
                @blur="stopEditing"
                @keyup.enter="stopEditing"
              />
            </template>
          </el-table-column>
          <el-table-column label="报价单价" align="center" width="100">
            <template #default="scope">
              <div v-if="!isEditing(scope.row, 'quotationPrice')" @click.stop="startEditing(scope.row, 'quotationPrice')">
                {{ scope.row.quotationPrice || '' }}
              </div>
              <el-input
                v-else
                v-model.number="scope.row.quotationPrice"
                size="mini"
                type="number"
                :min="0"
                @blur="stopEditing"
                @keyup.enter="stopEditing"
              />
            </template>
          </el-table-column>
          <el-table-column label="赠品" align="center" width="80">
            <template #default="scope">
              <el-switch v-model="scope.row.isGift" size="mini" />
            </template>
          </el-table-column>
          <el-table-column label="含税单价" align="center" width="100">
            <template #default="scope">
              <div v-if="!isEditing(scope.row, 'taxIncludedPrice')" @click.stop="startEditing(scope.row, 'taxIncludedPrice')">
                {{ scope.row.taxIncludedPrice || '' }}
              </div>
              <el-input
                v-else
                v-model.number="scope.row.taxIncludedPrice"
                size="mini"
                type="number"
                :min="0"
                @blur="stopEditing"
                @keyup.enter="stopEditing"
              />
            </template>
          </el-table-column>
          <el-table-column label="折扣率(%)" align="center" width="100">
            <template #default="scope">
              <div v-if="!isEditing(scope.row, 'discountRate')" @click.stop="startEditing(scope.row, 'discountRate')">
                {{ scope.row.discountRate || '' }}
              </div>
              <el-input
                v-else
                v-model.number="scope.row.discountRate"
                size="mini"
                type="number"
                :min="0"
                @blur="stopEditing"
                @keyup.enter="stopEditing"
              />
            </template>
          </el-table-column>
          <el-table-column label="折扣(折)" align="center" width="80">
            <template #default="scope">
              <div v-if="!isEditing(scope.row, 'discount')" @click.stop="startEditing(scope.row, 'discount')">
                {{ scope.row.discount || '' }}
              </div>
              <el-input
                v-else
                v-model.number="scope.row.discount"
                size="mini"
                type="number"
                :min="0"
                @blur="stopEditing"
                @keyup.enter="stopEditing"
              />
            </template>
          </el-table-column>
          <el-table-column label="折扣额" align="center" width="100">
            <template #default="scope">
              <div v-if="!isEditing(scope.row, 'discountAmount')" @click.stop="startEditing(scope.row, 'discountAmount')">
                {{ scope.row.discountAmount || '' }}
              </div>
              <el-input
                v-else
                v-model.number="scope.row.discountAmount"
                size="mini"
                type="number"
                :min="0"
                @blur="stopEditing"
                @keyup.enter="stopEditing"
              />
            </template>
          </el-table-column>
          <el-table-column label="折后单价" align="center" width="100">
            <template #default="scope">
              <div v-if="!isEditing(scope.row, 'discountedPrice')" @click.stop="startEditing(scope.row, 'discountedPrice')">
                {{ scope.row.discountedPrice || '' }}
              </div>
              <el-input
                v-else
                v-model.number="scope.row.discountedPrice"
                size="mini"
                type="number"
                :min="0"
                @blur="stopEditing"
                @keyup.enter="stopEditing"
              />
            </template>
          </el-table-column>
          <el-table-column label="折后含税单价" align="center" width="120">
            <template #default="scope">
              <div v-if="!isEditing(scope.row, 'discountedTaxPrice')" @click.stop="startEditing(scope.row, 'discountedTaxPrice')">
                {{ scope.row.discountedTaxPrice || '' }}
              </div>
              <el-input
                v-else
                v-model.number="scope.row.discountedTaxPrice"
                size="mini"
                type="number"
                :min="0"
                @blur="stopEditing"
                @keyup.enter="stopEditing"
              />
            </template>
          </el-table-column>
          <el-table-column label="金额" align="center" width="100">
            <template #default="scope">
              <div v-if="!isEditing(scope.row, 'amount')" @click.stop="startEditing(scope.row, 'amount')">
                {{ scope.row.amount || '' }}
              </div>
              <el-input
                v-else
                v-model.number="scope.row.amount"
                size="mini"
                type="number"
                :min="0"
                @blur="stopEditing"
                @keyup.enter="stopEditing"
              />
            </template>
          </el-table-column>
          <el-table-column label="税率(%)" align="center" width="100">
            <template #default="scope">
              <div v-if="!isEditing(scope.row, 'taxRate')" @click.stop="startEditing(scope.row, 'taxRate')">
                {{ scope.row.taxRate || '' }}
              </div>
              <el-input
                v-else
                v-model.number="scope.row.taxRate"
                size="mini"
                type="number"
                :min="0"
                @blur="stopEditing"
                @keyup.enter="stopEditing"
              />
            </template>
          </el-table-column>
          <el-table-column label="税额" align="center" width="100">
            <template #default="scope">
              <div v-if="!isEditing(scope.row, 'taxAmount')" @click.stop="startEditing(scope.row, 'taxAmount')">
                {{ scope.row.taxAmount || '' }}
              </div>
              <el-input
                v-else
                v-model.number="scope.row.taxAmount"
                size="mini"
                type="number"
                :min="0"
                @blur="stopEditing"
                @keyup.enter="stopEditing"
              />
            </template>
          </el-table-column>
          <el-table-column label="价税合计" align="center" width="120">
            <template #default="scope">
              <div v-if="!isEditing(scope.row, 'totalAmount')" @click.stop="startEditing(scope.row, 'totalAmount')">
                {{ scope.row.totalAmount || '' }}
              </div>
              <el-input
                v-else
                v-model.number="scope.row.totalAmount"
                size="mini"
                type="number"
                :min="0"
                @blur="stopEditing"
                @keyup.enter="stopEditing"
              />
            </template>
          </el-table-column>
          <el-table-column label="备注" align="center" width="150">
            <template #default="scope">
              <div v-if="!isEditing(scope.row, 'remark')" @click.stop="startEditing(scope.row, 'remark')">
                {{ scope.row.remark || '' }}
              </div>
              <el-input
                v-else
                v-model="scope.row.remark"
                size="mini"
                @blur="stopEditing"
                @keyup.enter="stopEditing"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="80">
            <template #default="scope">
              <el-button
                type="text"
                icon="el-icon-delete"
                @click="handleDeleteRow(scope.$index)"
              />
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 新增行按钮 -->
      <div class="add-row-btn">
        <el-button type="primary" icon="el-icon-plus" @click="addRow">新增行</el-button>
      </div>
    </div>

    <!-- 底部信息表单区域 -->
    <el-form :model="form" label-width="100px" class="bottom-info-form">
      <el-row :gutter="20">
        <el-col :span="4">
          <el-form-item label="交货方式">
            <el-select v-model="form.deliveryMethod" placeholder="请选择">
              <el-option label="自提" value="selfPickup" />
              <el-option label="送货上门" value="homeDelivery" />
              <el-option label="快递" value="express" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="收款条件">
            <el-select v-model="form.paymentTerms" placeholder="请选择">
              <el-option label="货到付款" value="cashOnDelivery" />
              <el-option label="预付款" value="advancePayment" />
              <el-option label="月结" value="monthlySettlement" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="备注">
            <el-input
              v-model="form.remark"
              type="textarea"
              :rows="2"
              placeholder="请输入备注信息"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 商品选择弹窗 -->
    <el-dialog title="选择商品" v-model="goodsDialogVisible" width="800px">
      <el-form :model="goodsSearch" inline class="mb-4">
        <el-form-item label="搜索">
          <el-input
            v-model="goodsSearch.keyword"
            placeholder="商品编号/名称/型号/品牌"
            clearable
            @keyup.enter="searchGoods"
          />
        </el-form-item>
        <el-form-item label="仓库">
          <el-select v-model="goodsSearch.warehouse" placeholder="(空)">
            <el-option label="空" value=""></el-option>
            <el-option label="主仓库" value="main"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="goodsSearch.showZeroStock">零库存商品</el-checkbox>
          <el-checkbox v-model="goodsSearch.showForbidden">显示禁用商品</el-checkbox>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchGoods">查询</el-button>
          <el-button @click="resetGoodsSearch">刷新</el-button>
        </el-form-item>
      </el-form>

      <div class="goods-container">
        <!-- 商品表格 -->
        <div class="goods-table">
          <el-table
            :data="goodsList"
            border
            @selection-change="handleGoodsSelection"
          >
            <el-table-column type="selection" width="50" />
            <el-table-column label="图片" width="60">
              <template #default="scope">
                <el-image
                  v-if="scope.row.image"
                  :src="scope.row.image"
                  style="width: 40px; height: 40px"
                  fit="cover"
                />
                <span v-else class="no-img">无图</span>
              </template>
            </el-table-column>
            <el-table-column prop="code" label="商品编号" width="120" />
            <el-table-column prop="brand" label="品牌" width="100" />
            <el-table-column prop="origin" label="产地" width="100" />
            <el-table-column prop="name" label="商品名称" width="200" />
          </el-table>

          <div class="dialog-footer mt-2">
            <el-pagination
              @size-change="handleGoodsSizeChange"
              @current-change="handleGoodsCurrentChange"
              :current-page="goodsPage.current"
              :page-sizes="[10, 20, 50]"
              :page-size="goodsPage.size"
              layout="total, sizes, prev, pager, next, jumper"
              :total="goodsTotal"
              style="float: left"
            ></el-pagination>
          </div>
        </div>

        <!-- 商品分类树 -->
        <div class="goods-category">
          <el-tree
            :data="categoryTree"
            :props="treeProps"
            default-expand-all
            show-checkbox
            @check="handleCategoryCheck"
          />
        </div>
      </div>

      <div class="dialog-footer mt-4">
        <el-button @click="goodsDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmGoods">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router';
// 表单数据
const form = ref({
  documentDate: '',
  quotationType: 'customer',
  quotationSubject: '',
  salesman: '',
  effectiveDate: [],
  customerAddress: '',
  isQuotation: false,
  scanGunInput: false,
  deliveryMethod: '',
  paymentTerms: '',
  remark: '',
});

// 实际数据（不含合计行），默认初始化5行
const actualData = ref([
  {
    index: 1,
    productName: '',
    productImage: '',
    brand: '',
    attribute: '',
    unit: '',
    warehouse: 'mainWarehouse',
    quantity: 0,
    baseUnit: '',
    baseQuantity: 0,
    quotationPrice: 0,
    isGift: false,
    taxIncludedPrice: 0,
    discountRate: 0,
    discount: 10,
    discountAmount: 0,
    discountedPrice: 0,
    discountedTaxPrice: 0,
    amount: 0,
    taxRate: 13,
    taxAmount: 0,
    totalAmount: 0,
    remark: '',
    editingField: null,
  },
  {
    index: 2,
    productName: '',
    productImage: '',
    brand: '',
    attribute: '',
    unit: '',
    warehouse: 'mainWarehouse',
    quantity: 0,
    baseUnit: '',
    baseQuantity: 0,
    quotationPrice: 0,
    isGift: false,
    taxIncludedPrice: 0,
    discountRate: 0,
    discount: 10,
    discountAmount: 0,
    discountedPrice: 0,
    discountedTaxPrice: 0,
    amount: 0,
    taxRate: 13,
    taxAmount: 0,
    totalAmount: 0,
    remark: '',
    editingField: null,
  },
  {
    index: 3,
    productName: '',
    productImage: '',
    brand: '',
    attribute: '',
    unit: '',
    warehouse: 'mainWarehouse',
    quantity: 0,
    baseUnit: '',
    baseQuantity: 0,
    quotationPrice: 0,
    isGift: false,
    taxIncludedPrice: 0,
    discountRate: 0,
    discount: 10,
    discountAmount: 0,
    discountedPrice: 0,
    discountedTaxPrice: 0,
    amount: 0,
    taxRate: 13,
    taxAmount: 0,
    totalAmount: 0,
    remark: '',
    editingField: null,
  },
  {
    index: 4,
    productName: '',
    productImage: '',
    brand: '',
    attribute: '',
    unit: '',
    warehouse: 'mainWarehouse',
    quantity: 0,
    baseUnit: '',
    baseQuantity: 0,
    quotationPrice: 0,
    isGift: false,
    taxIncludedPrice: 0,
    discountRate: 0,
    discount: 10,
    discountAmount: 0,
    discountedPrice: 0,
    discountedTaxPrice: 0,
    amount: 0,
    taxRate: 13,
    taxAmount: 0,
    totalAmount: 0,
    remark: '',
    editingField: null,
  },
  {
    index: 5,
    productName: '',
    productImage: '',
    brand: '',
    attribute: '',
    unit: '',
    warehouse: 'mainWarehouse',
    quantity: 0,
    baseUnit: '',
    baseQuantity: 0,
    quotationPrice: 0,
    isGift: false,
    taxIncludedPrice: 0,
    discountRate: 0,
    discount: 10,
    discountAmount: 0,
    discountedPrice: 0,
    discountedTaxPrice: 0,
    amount: 0,
    taxRate: 13,
    taxAmount: 0,
    totalAmount: 0,
    remark: '',
    editingField: null,
  },
]);

// 当前编辑的单元格
const currentEditing = ref({
  row: null,
  field: null,
});

// 计算属性：合计数据
const totalData = computed(() => {
  const dataRows = actualData.value;

  // 计算合计值
  let totalQuantity = 0;
  let totalAmount = 0;
  let totalTaxAmount = 0;
  let totalTotalAmount = 0;

  dataRows.forEach((row) => {
    totalQuantity += row.quantity || 0;
    totalAmount += row.amount || 0;
    totalTaxAmount += row.taxAmount || 0;
    totalTotalAmount += row.totalAmount || 0;
  });

  return {
    isTotalRow: true,
    index: '合计',
    productName: '',
    productImage: '',
    brand: '',
    attribute: '',
    unit: '',
    warehouse: '',
    quantity: totalQuantity,
    baseUnit: '',
    baseQuantity: 0,
    quotationPrice: 0,
    isGift: false,
    taxIncludedPrice: 0,
    discountRate: 0,
    discount: 0,
    discountAmount: 0,
    discountedPrice: 0,
    discountedTaxPrice: 0,
    amount: totalAmount,
    taxRate: 0,
    taxAmount: totalTaxAmount,
    totalAmount: totalTotalAmount,
    remark: '',
  };
});

// 计算属性：显示数据（含合计行）
const displayData = computed(() => [...actualData.value, totalData.value]);

// 检查单元格是否正在编辑
const isEditing = (row, field) => {
  return currentEditing.value.row === row && currentEditing.value.field === field;
};


const router = useRouter();
const recording = () => {
  router.push({ name: '报价单记录' });
}


// 开始编辑单元格
const startEditing = (row, field) => {
  // 不编辑合计行
  if (row.isTotalRow) return;

  currentEditing.value = { row, field };

  // 延迟聚焦，确保元素已渲染
  setTimeout(() => {
    const inputs = document.querySelectorAll(`.el-input__inner, .el-select__input`);
    if (inputs.length) {
      inputs[inputs.length - 1].focus();
    }
  }, 0);
};

// 停止编辑
const stopEditing = () => {
  currentEditing.value = { row: null, field: null };
};

// 单元格点击事件
const handleCellClick = (row, column, cell, event) => {
  // 如果点击的是已经显示的输入框，不处理
  if (
    event.target.classList.contains('el-input__inner') ||
    event.target.classList.contains('el-select__input')
  ) {
    return;
  }

  // 找到对应列的字段名
  const fieldMap = {
    '商品名称': 'productName',
    '品牌': 'brand',
    '属性': 'attribute',
    '单位': 'unit',
    '仓库': 'warehouse',
    '数量': 'quantity',
    '基本单位': 'baseUnit',
    '基本数量': 'baseQuantity',
    '报价单价': 'quotationPrice',
    '含税单价': 'taxIncludedPrice',
    '折扣率(%)': 'discountRate',
    '折扣(折)': 'discount',
    '折扣额': 'discountAmount',
    '折后单价': 'discountedPrice',
    '折后含税单价': 'discountedTaxPrice',
    '金额': 'amount',
    '税率(%)': 'taxRate',
    '税额': 'taxAmount',
    '价税合计': 'totalAmount',
    '备注': 'remark',
  };

  const field = fieldMap[column.label];
  if (field) {
    startEditing(row, field);
  }
};

// 新增行
const addRow = () => {
  const newRow = {
    index: actualData.value.length + 1,
    productName: '',
    productImage: '',
    brand: '',
    attribute: '',
    unit: '',
    warehouse: 'mainWarehouse',
    quantity: 0,
    baseUnit: '',
    baseQuantity: 0,
    quotationPrice: 0,
    isGift: false,
    taxIncludedPrice: 0,
    discountRate: 0,
    discount: 10,
    discountAmount: 0,
    discountedPrice: 0,
    discountedTaxPrice: 0,
    amount: 0,
    taxRate: 13,
    taxAmount: 0,
    totalAmount: 0,
    remark: '',
    editingField: null,
  };

  actualData.value.push(newRow);
};

// 删除行
const handleDeleteRow = (index) => {
  // 确保不删除合计行
  if (index >= actualData.value.length) {
    ElMessage.warning('不能删除合计行');
    return;
  }

  if (actualData.value.length === 1) {
    ElMessage.warning('至少保留一行数据');
    return;
  }

  ElMessageBox.confirm('确定要删除此行吗？', '提示', {
    type: 'warning',
  })
    .then(() => {
      actualData.value.splice(index, 1);
            // 更新行号
            actualData.value.forEach((row, idx) => {
        row.index = idx + 1;
      });
      ElMessage.success('删除成功');
    })
    .catch(() => {
      ElMessage.info('已取消删除');
    });
};

// 批量修改数量
const handleBatchModify = () => {
  ElMessageBox.prompt('请输入要设置的数量', '批量修改', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /^\d+$/,
    inputErrorMessage: '请输入数字',
  })
    .then(({ value }) => {
      if (value) {
        const quantity = Number(value);
        actualData.value.forEach((row) => {
          row.quantity = quantity;
        });
        ElMessage.success('批量修改成功');
      }
    })
    .catch(() => {
      ElMessage.info('已取消批量修改');
    });
};

// 保存并新增
const handleSaveAndNew = () => {
  ElMessage.success('保存并新增成功');
};

// 保存
const handleSave = () => {
  ElMessage.success('保存成功');
};

// 审核
const handleApprove = () => {
  ElMessage.success('审核成功');
};

// 商品选择弹窗相关
const goodsDialogVisible = ref(false);
const goodsSearch = reactive({
  keyword: '',
  warehouse: '',
  showZeroStock: false,
  showForbidden: false,
});
const goodsList = ref([
  {
    code: 'SP001',
    name: '商品1',
    brand: '品牌1',
    origin: '产地1',
  
  },
  {
    code: 'SP002',
    name: '商品2',
    brand: '品牌2',
    origin: '产地2',
  
  },
  {
    code: 'SP003',
    name: '商品3',
    brand: '品牌3',
    origin: '产地3',
 
  },
  {
    code: 'SP004',
    name: '商品4',
    brand: '品牌4',
    origin: '产地4',
 
  },
  {
    code: 'SP005',
    name: '商品5',
    brand: '品牌5',
    origin: '产地5',
  
  },
]);
const goodsTotal = ref(50);
const goodsPage = reactive({
  current: 1,
  size: 10,
});
const selectedGoods = ref([]);
const categoryTree = ref([
  {
    id: 1,
    label: '全部',
    children: [
      {
        id: 2,
        label: '食品饮料',
        children: [
          { id: 3, label: '休闲食品' },
          { id: 4, label: '饮料' },
        ],
      },
      {
        id: 5,
        label: '日用品',
        children: [
          { id: 6, label: '家居清洁' },
          { id: 7, label: '个人护理' },
        ],
      },
      {
        id: 8,
        label: '生鲜',
        children: [
          { id: 9, label: '水果' },
          { id: 10, label: '肉类' },
        ],
      },
    ],
  },
]);
const treeProps = ref({
  children: 'children',
  label: 'label',
});

// 打开商品选择弹窗
const openGoodsDialog = () => {
  goodsDialogVisible.value = true;
};

// 搜索商品
const searchGoods = () => {
  // 模拟搜索逻辑
  console.log('搜索商品:', goodsSearch);
  // 这里可以添加实际的搜索请求
};

// 重置搜索条件
const resetGoodsSearch = () => {
  goodsSearch.keyword = '';
  goodsSearch.warehouse = '';
  goodsSearch.showZeroStock = false;
  goodsSearch.showForbidden = false;
  searchGoods();
};

// 处理商品选择
const handleGoodsSelection = (val) => {
  selectedGoods.value = val;
};

// 处理分类树选择
const handleCategoryCheck = (data, checked) => {
  console.log('分类树选择:', data, checked);
  // 这里可以添加根据分类筛选商品的逻辑
};

// 处理分页大小变化
const handleGoodsSizeChange = (size) => {
  goodsPage.size = size;
  searchGoods();
};

// 处理页码变化
const handleGoodsCurrentChange = (current) => {
  goodsPage.current = current;
  searchGoods();
};

// 确认选择商品
const confirmGoods = () => {
  if (selectedGoods.value.length === 0) {
    ElMessage.warning('请选择商品');
    return;
  }

  // 将选中的商品添加到报价单中
  selectedGoods.value.forEach((goods) => {
    // 检查是否已添加相同商品
    const exists = actualData.value.some(
      (row) => row.productCode === goods.code
    );
    if (!exists) {
      const newRow = {
        index: actualData.value.length + 1,
        productCode: goods.code,
        productName: goods.name,
        productImage: goods.image,
        brand: goods.brand,
        attribute: '',
        unit: '',
        warehouse: 'mainWarehouse',
        quantity: 1,
        baseUnit: '',
        baseQuantity: 1,
        quotationPrice: 0,
        isGift: false,
        taxIncludedPrice: 0,
        discountRate: 0,
        discount: 10,
        discountAmount: 0,
        discountedPrice: 0,
        discountedTaxPrice: 0,
        amount: 0,
        taxRate: 13,
        taxAmount: 0,
        totalAmount: 0,
        remark: '',
        editingField: null,
      };
      actualData.value.push(newRow);
    }
  });

  goodsDialogVisible.value = false;
  ElMessage.success(`成功添加 ${selectedGoods.value.length} 个商品`);
};

// 生命周期钩子
onMounted(() => {
  // 初始化合计数据
});
</script>

<style scoped>
.quotation-page {
  padding: 20px;
  background-color: #fff;
}
.top-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.title-area {
  display: flex;
  align-items: center;
  gap: 20px;
}
.page-title {
  font-size: 18px;
  font-weight: bold;
}
.doc-number {
  color: #666;
}
.btn-group {
  display: flex;
  gap: 10px;
}
.base-info-form,
.bottom-info-form {
  margin-bottom: 20px;
}
.table-wrapper {
  margin-bottom: 20px;
}
.table-scroll {
  overflow: auto;
  border: 1px solid #ebeef5;
}
.el-table {
  --el-table-header-text-color: #333;
  --el-table-row-hover-bg-color: #fafafa;
}
.header-with-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
}
.add-row-btn {
  text-align: right;
  margin-top: 10px;
  margin-bottom: 5px;
}

/* 合计行样式 */
.el-table .el-table__row.is-total-row {
  background-color: #fff8dc;
  font-weight: bold;
  font-size: 12px;
}
.el-table .el-table__row.is-total-row .cell {
  padding: 6px 0;
}

/* 可编辑单元格样式 */
.editable-cell {
  cursor: pointer;
  min-height: 24px;
}

/* 商品选择弹窗样式 */
.goods-container {
  display: flex;
  gap: 10px;
  height: 400px;
}
.goods-table {
  flex: 3;
  display: flex;
  flex-direction: column;
}
.goods-category {
  flex: 1;
  border: 1px solid #ebeef5;
  padding: 10px;
  overflow: auto;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
.no-img {
  display: inline-block;
  width: 40px;
  height: 40px;
  line-height: 40px;
  text-align: center;
  background-color: #f5f7fa;
  color: #909399;
  border-radius: 4px;
}
.mt-2 {
  margin-top: 10px;
}
.mt-4 {
  margin-top: 20px;
}
</style>